<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
<!--            <el-form-item label="所属机构id" prop="organId">-->
<!--              <el-input v-model="queryParams.organId" placeholder="请输入所属机构id" clearable @keyup.enter="handleQuery" />-->
<!--            </el-form-item>-->
            <el-form-item label="商家名称" prop="merName">
              <el-input v-model="queryParams.merName" placeholder="请输入商家名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['shopping:mer:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="merList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="所属机构" align="center" prop="organName" />
        <el-table-column label="商家名称" align="center" prop="merName" />
        <el-table-column label="商铺编号" align="center" prop="merNo" />
        <el-table-column label="商家logo" align="center" prop="merLogo" />
        <el-table-column label="商家地址" align="center" prop="address" />
        <el-table-column label="联系人" align="center" prop="leaderName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['shopping:mer:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['shopping:mer:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改服务商家对话框 -->
    <el-drawer v-model="dialog.visible" size="60%" :title="dialog.title" :direction="direction"
               close-on-click-modal>
      <el-form ref="merFormRef" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属机构" prop="organId">
              <el-select v-model="form.organId" placeholder="请选择所属机构" filterable clearable style="width: 100%;">
                <el-option v-for="item in organList"
                           :key="item.id" :label="item.organName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="所属区划" prop="provinceArray">
              <AreaOptions ref="AreaOptions1" v-if="dialog.visible" :modelValue="form.provinceArray" :isHasDis="1"
                           @change="handleChangeProvince" @expand-change="handleExpandChange"></AreaOptions>
            </el-form-item>
            <el-form-item label="商家名称" prop="merName">
              <el-input v-model="form.merName" placeholder="请输入商家名称" />
            </el-form-item>
            <el-form-item label="商家状态" prop="state">
              <!--          0 - 正常运行 1 - 停止服务-->
              <el-radio-group v-model="form.state">
                <el-radio :value="0" :label="0">正常运行</el-radio>
                <el-radio :value="1" :label="1">停止服务</el-radio>
              </el-radio-group>
            </el-form-item>
            <!--        <el-form-item label="主分类id" prop="cateId">-->
            <!--          <el-input v-model="form.cateId" placeholder="请输入主分类id" />-->
            <!--        </el-form-item>-->
            <!--        <el-form-item label="子分类id" prop="cateChildId">-->
            <!--          <el-input v-model="form.cateChildId" placeholder="请输入子分类id" />-->
            <!--        </el-form-item>-->
            <el-form-item label="经纬度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度" style="width: 49%"/>
              <el-input v-model="form.latitude" placeholder="请输入纬度"  style="margin-left:5px;width: 49%"/>
            </el-form-item>
            <el-form-item label="商家地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入商家地址" />
            </el-form-item>
            <el-form-item label="联系人" prop="leaderName">
              <el-input v-model="form.leaderName" placeholder="请输入联系人" />
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入联系电话" />
            </el-form-item>
            <!--        <el-form-item label="商家邮箱" prop="email">-->
            <!--          <el-input v-model="form.email" placeholder="请输入商家邮箱" />-->
            <!--        </el-form-item>-->
            <el-form-item label="商家星级" prop="serviceStar">
              <!--          <el-input v-model="form.serviceStar" placeholder="请输入商家星级" />-->
              <el-rate v-model="form.serviceStar" :colors="colors" clearable />
            </el-form-item>
            <!--        <el-form-item label="关键词  多个逗号分隔" prop="keyWord">-->
            <!--          <el-input v-model="form.keyWord" placeholder="请输入关键词  多个逗号分隔" />-->
            <!--        </el-form-item>-->
            <el-form-item label="商家介绍" prop="introduce">
              <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="LOGO" prop="merLogoPath">
              <single-pic v-model="form.merLogoPath" type="image" :img-list="[form.merLogoPath]" @handleChecked="chooseImg" :uploadType="2"
                          :num="1" :width="120" :height="120" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div style="margin: 20px;width:95%;height:60vh;">
              <TianDiTu :zoom="12" :label-title="form.merName"
                        :default-lat="form.latitude" :default-lng="form.longitude"
                        @pickLngLat="pickLngLat"></TianDiTu>
            </div>
          </el-col>
        </el-row>

<!--        <el-form-item label="营业执照" prop="creditCode">-->
<!--          <el-input v-model="form.creditCode" placeholder="请输入营业执照" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="执照图片" prop="codeImg">-->
<!--          <el-input v-model="form.codeImg" placeholder="请输入执照图片" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="法人身份证正面" prop="idCardImgBefore">-->
<!--          <el-input v-model="form.idCardImgBefore" placeholder="请输入法人身份证正面" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="法人身份证反面" prop="idCardImgAfter">-->
<!--          <el-input v-model="form.idCardImgAfter" placeholder="请输入法人身份证反面" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="审核状态 0 -待审核 1-  审核通过 2 - 审核失败" prop="checkState">-->
<!--          <el-input v-model="form.checkState" placeholder="请输入审核状态 0 -待审核 1-  审核通过 2 - 审核失败" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="审核结果" prop="checkResult">-->
<!--          <el-input v-model="form.checkResult" placeholder="请输入审核结果" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="合同图片" prop="heTongPic">-->
<!--            <el-input v-model="form.heTongPic" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="电子签名图片" prop="signImg">-->
<!--          <el-input v-model="form.signImg" placeholder="请输入电子签名图片" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="商家二维码" prop="qrCode">-->
<!--          <el-input v-model="form.qrCode" placeholder="请输入商家二维码" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="结算银行名称" prop="bankName">-->
<!--          <el-input v-model="form.bankName" placeholder="请输入结算银行名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="结算银行卡号" prop="bankCardNo">-->
<!--          <el-input v-model="form.bankCardNo" placeholder="请输入结算银行卡号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="结算银行卡账户名" prop="bankRealName">-->
<!--          <el-input v-model="form.bankRealName" placeholder="请输入结算银行卡账户名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="邀请人id" prop="agId">-->
<!--          <el-input v-model="form.agId" placeholder="请输入邀请人id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="推广员id" prop="promoterId">-->
<!--          <el-input v-model="form.promoterId" placeholder="请输入推广员id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="支付平台  0 - 微信  1 - 农商行" prop="payPlatform">-->
<!--          <el-input v-model="form.payPlatform" placeholder="请输入支付平台  0 - 微信  1 - 农商行" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="第三方支付商户id" prop="payPlatformId">-->
<!--          <el-input v-model="form.payPlatformId" placeholder="请输入第三方支付商户id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="地理围栏经纬度多边形点集合" prop="points">-->
<!--            <el-input v-model="form.points" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Mer" lang="ts">
import { listMer, getMer, delMer, addMer, updateMer } from '@/api/shopping/mer';
import { MerVO, MerQuery, MerForm } from '@/api/shopping/mer/types';
import {DrawerProps} from "element-plus";
import SinglePic from "@/components/SingleMaterial/single.vue";
import {OrganVO} from "@/api/shopping/organ/types";
import {noPageListOrgan} from "@/api/shopping/organ";

// 天地图
import TianDiTu from "@/components/TianDiTuLayer/index.vue"

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const organList = ref<OrganVO[]>([]);
const direction = ref<DrawerProps['direction']>('rtl');
const merList = ref<MerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])

const queryFormRef = ref<ElFormInstance>();
const merFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: MerForm = {
  id: undefined,
  organId: undefined,
  merName: undefined,
  merNo: undefined,
  merLogo: undefined,
  shopType: undefined,
  state: undefined,
  cateId: undefined,
  cateChildId: undefined,
  longitude: undefined,
  latitude: undefined,
  provId: undefined,
  cityId: undefined,
  districtId: undefined,
  provName: undefined,
  cityName: undefined,
  districtName: undefined,
  address: undefined,
  leaderName: undefined,
  telephone: undefined,
  email: undefined,
  createTime: undefined,
  serviceStar: undefined,
  keyWord: undefined,
  introduce: undefined,
  creditCode: undefined,
  codeImg: undefined,
  idCardImgBefore: undefined,
  idCardImgAfter: undefined,
  checkState: undefined,
  checkResult: undefined,
  heTongPic: undefined,
  signImg: undefined,
  qrCode: undefined,
  bankName: undefined,
  bankCardNo: undefined,
  bankRealName: undefined,
  agId: undefined,
  promoterId: undefined,
  payPlatform: undefined,
  payPlatformId: undefined,
  points: undefined,
  merLogoPath: undefined,
  provinceArray: [],
}
const data = reactive<PageData<MerForm, MerQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    organId: undefined,
    merName: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    organId: [
      { required: true, message: "所属机构id不能为空", trigger: "blur" }
    ],
    merName: [
      { required: true, message: "商家名称不能为空", trigger: "blur" }
    ],
    merNo: [
      { required: true, message: "商铺编号不能为空", trigger: "blur" }
    ],
    provinceArray: [
      { required: true, message: "请选择所属区划", trigger: "blur" }
    ],
    merLogo: [
      { required: true, message: "商家logo不能为空", trigger: "blur" }
    ],
    shopType: [
      { required: true, message: "商家类型  0 - 普通商家不能为空", trigger: "change" }
    ],
    state: [
      { required: true, message: "商家状态  0 - 正常运行 1 - 停止服务不能为空", trigger: "blur" }
    ],
    cateId: [
      { required: true, message: "主分类id不能为空", trigger: "blur" }
    ],
    cateChildId: [
      { required: true, message: "子分类id不能为空", trigger: "blur" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ],
    provId: [
      { required: true, message: "所在省份id不能为空", trigger: "blur" }
    ],
    cityId: [
      { required: true, message: "所在城市id不能为空", trigger: "blur" }
    ],
    districtId: [
      { required: true, message: "所在区县不能为空", trigger: "blur" }
    ],
    provName: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    cityName: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    districtName: [
      { required: true, message: "区县名称不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "商家地址不能为空", trigger: "blur" }
    ],
    leaderName: [
      { required: true, message: "联系人不能为空", trigger: "blur" }
    ],
    telephone: [
      { required: true, message: "联系电话不能为空", trigger: "blur" }
    ],
    email: [
      { required: true, message: "商家邮箱不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "添加时间不能为空", trigger: "blur" }
    ],
    serviceStar: [
      { required: true, message: "商家星级不能为空", trigger: "blur" }
    ],
    keyWord: [
      { required: true, message: "关键词  多个逗号分隔不能为空", trigger: "blur" }
    ],
    introduce: [
      { required: true, message: "商家介绍不能为空", trigger: "blur" }
    ],
    creditCode: [
      { required: true, message: "营业执照不能为空", trigger: "blur" }
    ],
    codeImg: [
      { required: true, message: "执照图片不能为空", trigger: "blur" }
    ],
    idCardImgBefore: [
      { required: true, message: "法人身份证正面不能为空", trigger: "blur" }
    ],
    idCardImgAfter: [
      { required: true, message: "法人身份证反面不能为空", trigger: "blur" }
    ],
    checkState: [
      { required: true, message: "审核状态 0 -待审核 1-  审核通过 2 - 审核失败不能为空", trigger: "blur" }
    ],
    checkResult: [
      { required: true, message: "审核结果不能为空", trigger: "blur" }
    ],
    heTongPic: [
      { required: true, message: "合同图片不能为空", trigger: "blur" }
    ],
    signImg: [
      { required: true, message: "电子签名图片不能为空", trigger: "blur" }
    ],
    qrCode: [
      { required: true, message: "商家二维码不能为空", trigger: "blur" }
    ],
    bankName: [
      { required: true, message: "结算银行名称不能为空", trigger: "blur" }
    ],
    bankCardNo: [
      { required: true, message: "结算银行卡号不能为空", trigger: "blur" }
    ],
    bankRealName: [
      { required: true, message: "结算银行卡账户名不能为空", trigger: "blur" }
    ],
    agId: [
      { required: true, message: "邀请人id不能为空", trigger: "blur" }
    ],
    promoterId: [
      { required: true, message: "推广员id不能为空", trigger: "blur" }
    ],
    payPlatform: [
      { required: true, message: "支付平台  0 - 微信  1 - 农商行不能为空", trigger: "blur" }
    ],
    payPlatformId: [
      { required: true, message: "第三方支付商户id不能为空", trigger: "blur" }
    ],
    points: [
      { required: true, message: "地理围栏经纬度多边形点集合不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询服务商家列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMer(queryParams.value);
  merList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

const getOrganList = async()=>{
  const res = await noPageListOrgan(queryParams.value);
  organList.value = res.data;
}

const chooseImg = (data) => {
  console.log("mer chooseImg",data);
  if(data.length > 0) {
    form.value.merLogoPath = data[0].imgUrl
    form.value.merLogo = data[0].url;
  }
};

const pickLngLat = (e) => {
  console.log('getLngLat e === ', e)
  form.value.longitude = e.lng.toFixed(6);
  form.value.latitude = e.lat.toFixed(6);
};

const handleChangeProvince = (e) => {
  console.log('handleChangeProvince',e);
  form.value.provinceArray = e;
};

// TODO：各父级选项值组成的数组
const handleExpandChange = (e) => {
  console.log(e);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  merFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: MerVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getOrganList();

  form.value.longitude = 119.513841;
  form.value.latitude =  35.43233;
  dialog.visible = true;
  dialog.title = "添加服务商家";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: MerVO) => {
  reset();
  getOrganList();
  const _id = row?.id || ids.value[0]
  const res = await getMer(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改服务商家";
}

/** 提交按钮 */
const submitForm = () => {
  merFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMer(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addMer(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: MerVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除服务商家编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delMer(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('shopping/mer/export', {
    ...queryParams.value
  }, `mer_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
